//
//  MineSetViewController.m
//  MyvIEW
//
//  Created by Macbook on 28/7/17.
//  Copyright © 2017年 huyu. All rights reserved.
//

#import "MineSetViewController.h"
#import <AliyunOSSiOS/OSSService.h>
#import <CoreLocation/CoreLocation.h>

@interface MineSetViewController ()<UITextFieldDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,MBProgressHUDDelegate,UITextViewDelegate,CLLocationManagerDelegate>{
    UIImagePickerController *_pickController;
    AFHTTPRequestOperationManager *manager;
    NSString *_message;
    NSString *_url;
    MBProgressHUD *_HUD;

}
@property (weak, nonatomic) IBOutlet UITextField *ShopNameFiled;
@property (weak, nonatomic) IBOutlet UITextField *MobFiled;
@property (weak, nonatomic) IBOutlet UITextView *DesTextView;
@property (weak, nonatomic) IBOutlet UILabel *LocationLab;
@property (weak, nonatomic) IBOutlet UIButton *SaveBut;
@property (weak, nonatomic) IBOutlet UIImageView *PhotoImg;
@property (strong, nonatomic) OSSClient *client;
@property(nonatomic,strong)CLLocationManager *locationManager;
@end

@implementation MineSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"商家信息";
    self.view.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fingerTapped:)];
    
    [self.view addGestureRecognizer:singleTap];
    UIButton *backbutton = [[UIButton alloc]initWithFrame:CGRectMake(10, 20, 15, 25)];
    [backbutton setBackgroundImage:[UIImage imageNamed:@"香草园地-发布信息_03@2x"] forState:UIControlStateNormal];
    [backbutton addTarget:self action:@selector(goBacktoUp) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithCustomView:backbutton];
    self.navigationItem.leftBarButtonItem = backItem;
    //初始化pickerController
    _pickController = [[UIImagePickerController alloc]init];
    _pickController.view.backgroundColor = [UIColor orangeColor];
    _pickController.delegate = self;
    _pickController.allowsEditing = YES;
    NSString *city = [USERDEFAULT objectForKey:@"city"];

    if ([city isEqualToString:@""]) {
        // 判断定位操作是否被允许
        if([CLLocationManager locationServicesEnabled]) {
            //定位初始化
            _locationManager=[[CLLocationManager alloc] init];
            _locationManager.delegate=self;
            _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
            _locationManager.distanceFilter=10;
            
            [_locationManager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据（iOS8定位需要）
            
//            [_locationManager startUpdatingLocation];//开启定位
        }else {
            //提示用户无法进行定位操作
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"定位不成功 ,请确认开启定位" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alertView show];
        }
        // 开始定位
        [_locationManager startUpdatingLocation];
        
    }else{
        _LocationLab.text = city;
    }
    [self initALi];
}
-(void)viewWillAppear:(BOOL)animated{
    [self ui];

}
-(BOOL) textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    
    return YES;
    
}

-(void)fingerTapped:(UITapGestureRecognizer *)gestureRecognizer

{
    
    [self.view endEditing:YES];
    
}
- (void)initALi
{
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:@"9eEB2RAzLHaW5Asu" secretKey:@"YdbWni4mRxDy0ndN6g4xH9ErpkV5ZT"];
    
    OSSClientConfiguration * conf = [OSSClientConfiguration new];
    
    // 网络请求遇到异常失败后的重试次数
    conf.maxRetryCount = 3;
    
    // 网络请求的超时时间
    conf.timeoutIntervalForRequest =30;
    
    // 允许资源传输的最长时间
    conf.timeoutIntervalForResource =24 * 60 * 60;
    
    // 你的阿里地址前面通常是这种格式 ：http://oss……
    _client = [[OSSClient alloc] initWithEndpoint:@"http://oss-cn-hangzhou.aliyuncs.com" credentialProvider:credential];
}
-(void)goBacktoUp{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)ui{
    
    NSString *name = [USERDEFAULT objectForKey:@"name"];
    NSString *mobile = [USERDEFAULT objectForKey:@"mobile"];
    NSString *summary = [USERDEFAULT objectForKey:@"summary"];
    NSString *head_image = [USERDEFAULT objectForKey:@"head_image"];

    _MobFiled.text = mobile;

        _ShopNameFiled.text = name;
    
//    if ([summary isEqualToString:@""]) {
//
//    }else{
        _DesTextView.text = summary;
        
//    }
    _PhotoImg.userInteractionEnabled = YES;
    _PhotoImg.clipsToBounds = YES;
    _PhotoImg.layer.cornerRadius = 32;
    _PhotoImg.contentMode = UIViewContentModeScaleAspectFill;
    [_PhotoImg sd_setImageWithURL:[NSURL URLWithString:head_image] placeholderImage:[UIImage imageNamed:@"我的_03.png"]];
    

    
}
#pragma mark-CLLocationManagerDelegate
 /**
      *  当定位到用户的位置时，就会调用（调用的频率比较频繁）
      */
 -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
 {
         //locations数组里边存放的是CLLocation对象，一个CLLocation对象就代表着一个位置
        CLLocation *loc = [locations firstObject];
    
         //维度：loc.coordinate.latitude
         //经度：loc.coordinate.longitude
         NSLog(@"纬度=%f，经度=%f",loc.coordinate.latitude,loc.coordinate.longitude);
         NSLog(@"%lu",(unsigned long)locations.count);
     CLGeocoder *geocoder = [[CLGeocoder alloc] init];
     //根据经纬度反向地理编译出地址信息
     [geocoder reverseGeocodeLocation:loc completionHandler:^(NSArray *array, NSError *error)
      {
          if (array.count > 0)
          {
              CLPlacemark *placemark = [array objectAtIndex:0];
              //NSLog(@%@,placemark.name);//具体位置
              //获取城市
              NSString *city = placemark.locality;
              if (!city) {
                  //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                  city = placemark.administrativeArea;
              }
              _LocationLab.text = city;
              NSLog(@"定位完成:%@",city);
              //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
              [self.locationManager stopUpdatingLocation];
          }else if (error == nil && [array count] == 0)
          {
              NSLog(@"No results were returned.");
          }else if (error != nil)
          {
              NSLog(@"An error occurred = %@", error);
          }
      }];
    
     }
- (IBAction)PhotoBut:(id)sender {
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"选择头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
    [actionSheet showInView:[UIApplication sharedApplication].keyWindow];
}
#pragma mark -- UITaction协议方法
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {//相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            NSLog(@"支持相机");
            [self makePhoto];
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请在设置-->隐私-->相机，中开启本应用的相机访问权限！！" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"我知道了", nil];
            [alert show];
        }
    }else if (buttonIndex == 1){//相片
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
        {
            NSLog(@"支持相册");
            [self choosePicture];
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请在设置-->隐私-->照片，中开启本应用的相机访问权限！！" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"我知道了", nil];
            [alert show];
        }
    }
}
//跳转到imagePicker里
- (void)makePhoto
{
    _pickController.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:_pickController animated:YES completion:nil];
}
//跳转到相册
- (void)choosePicture
{
    _pickController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [self presentViewController:_pickController animated:YES completion:nil];
    
    
}//用户取消退出picker时候调用
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    
    
    [_pickController dismissViewControllerAnimated:YES completion:^{
        
    }];
}
//用户选中图片之后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
//    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
//    [self performSelector:@selector(saveImage:) withObject:img afterDelay:0.1];

    
    UIImage *userImage = [self fixOrientation:[info objectForKey:@"UIImagePickerControllerOriginalImage"]];
    
    userImage = [self scaleImage:userImage toScale:0.3];
    
    //保存图片
    // [self saveImage:userImage name:@"imageIcon"];
    
    [_pickController dismissViewControllerAnimated:YES completion:^{
        
        
    }];
    
    //照片上传
    [self saveImage:userImage];

}//缩放图片
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    //    NSLog(@"%@",NSStringFromCGSize(scaledImage.size));
    return scaledImage;
}
//修正照片方向(手机转90度方向拍照)
- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

- (void)saveImage:(UIImage *)image {
    // 图片名
    NSString *imageName = [NSString stringWithFormat:@"%@.jpg", [[NSUUID UUID] UUIDString]];
    
    NSData *ImageData =UIImageJPEGRepresentation(image,0.5);;
    [self updateToALi:ImageData imageName:imageName];
}

- (void)updateToALi:(NSData *)data imageName:(NSString *)imageName
{
    _HUD=[MBProgressHUD showHUDAddedTo:self.view animated:YES];
    _HUD.mode=MBProgressHUDModeIndeterminate;//枚举类型不同的效果
    _HUD.delegate = self;
    _HUD.labelText=@"正在上传头像";
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    
    put.bucketName =@"hd3p";
    put.objectKey =imageName;
    
    put.uploadingData = data; // 直接上传NSData
    
    put.uploadProgress = ^(int64_t bytesSent,int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        NSLog(@"。。。。%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    
    OSSTask * putTask = [_client putObject:put];
    
    // 上传阿里云
    [putTask continueWithBlock:^id(OSSTask *task) {
        if (!task.error) {
            _url = [NSString stringWithFormat:@"http://hd3p.oss-cn-hangzhou.aliyuncs.com/%@",imageName];
            [USERDEFAULT setObject:_url forKey:@"head_image"];
            NSLog(@"upload object success! %@",_url);
            [self performSelectorOnMainThread:@selector(delayMe) withObject:nil waitUntilDone:YES];
       

        } else {
            
            NSLog(@"upload object failed, error: %@" , task.error);
        }
        return nil;
    }];
    
}
-(void)delayMe{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    [self ui];
}
- (IBAction)LocationBut:(id)sender {
    NSLog(@"点击换地址");
}
- (IBAction)SaveBut:(id)sender {
    if (_ShopNameFiled.text.length==0) {
        [self.view makeToast:@"请填写店铺名称"];
    }else{
        NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
        NSString *uid = [defaults objectForKey:@"shop_guid"];
        
        AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
        manger.responseSerializer = [AFJSONResponseSerializer serializer];
        manger.requestSerializer = [AFJSONRequestSerializer serializer];
        manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/ttml", nil];
        NSString *Url = [NSString stringWithFormat:@"%@shop/selfInfosUpdate?shop_guid=%@",ServiceURL2,uid];
        NSString *limageu = [USERDEFAULT objectForKey:@"head_image"];
        NSDictionary *params = @{@"head_image":limageu,@"summary":_DesTextView.text,@"name":_ShopNameFiled.text};
        NSLog(@"Url==%@",Url);

        
        
        [manger POST:Url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            [self performSelectorOnMainThread:@selector(delayMeto) withObject:nil waitUntilDone:YES];
            NSLog(@"%@",responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        }];
    }
    



}
-(void)delayMeto{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
